/******************************************************************************* 
 * Copyright (c) 2008 xored software, Inc.  
 * 
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Eclipse Public License v1.0 
 * which accompanies this distribution, and is available at 
 * http://www.eclipse.org/legal/epl-v10.html  
 * 
 * Contributors: 
 *     xored software, Inc. - initial API and Implementation (Yuri Strot) 
 *******************************************************************************/
package com.xored.glance.ui.sources;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

/**
 * @author Yuri Strot
 * 
 */
public class ColorManager implements IPropertyChangeListener {

	public static final String ANNOTATION_ID = "com.xored.glance.ui.highlight";
	public static final String COLOR_BACKGROUND = "glanceColorBackground";

	@SuppressWarnings("deprecation")
	public static IPreferenceStore getStore() {
		return ((AbstractUIPlugin) Platform.getPlugin("org.eclipse.ui.editors"))
				.getPreferenceStore();
	}

	public static ColorManager getInstance() {
		if (instance == null)
			instance = new ColorManager();
		return instance;
	}

	public Color getBackgroundColor() {
		return color;
	}

	public void propertyChange(PropertyChangeEvent event) {
		if (COLOR_BACKGROUND.equals(event.getProperty())) {
			updateColor();
		}
	}

	private ColorManager() {
		getStore().addPropertyChangeListener(this);
		updateColor();
	}

	private void updateColor() {
		if (color != null) {
			color.dispose();
			color = null;
		}

		Display display = PlatformUI.getWorkbench().getDisplay();
		IPreferenceStore store = getStore();
		RGB rgb = PreferenceConverter.getColor(store, COLOR_BACKGROUND);
		color = new Color(display, rgb);
	}

	private static ColorManager instance;
	private Color color;

}
